console.inspectEnable = true
import coap from 'coap';
import { ICallBack } from '../../interfaces/api.interface';

class CoapManager {
  /* 获取coap服务指定路径的内容 */
  get(url: string, path = '/', cb: ICallBack) {
    coap.request(url, (client) => {
      client.on('response', ({ }, res: any) => {
        const data = Buffer.isBuffer(res.payload) ? res.payload.toString() : res.payload
        console.info('coap get response payload:', data)
        cb({ result: true, message: '操作成功！', data })
      })

      client.on('error', (e) => {
        console.log('coap error.', e)
        cb({ result: false, message: '获取Coap指定路径内容失败！' })
      })
    }, { method: 'GET', path })
  }

  /* 修改coap服务指定路径的内容 */
  put(url: string, path = '/', data: string, cb: ICallBack) {
    coap.request(url, (client) => {
      client.on('response', ({ }, res: any) => {
        const data = Buffer.isBuffer(res.payload) ? res.payload.toString() : res.payload
        console.info('coap put response payload:', data);
        cb({ result: true, message: '操作成功！' })
      })

      client.on('error', (e) => {
        console.log('coap put error.', e)
        cb({ result: false, message: '修改Coap指定路径内容失败！' })
      })
    }, { method: 'PUT', path, payload: data })
  }
}

export default new CoapManager();